package model

import (
	"fmt"
	"net"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func (api *Server) IndexHtml() {
	api.Run.GET("/", func(c *gin.Context) {
		// 获取客户端真实IP地址
		clientIP := api.getClientIP(c)
		
		// 设置允许的跨域头部
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		
		// 返回HTML渲染
		c.Header("Content-Type", "text/html; charset=utf-8")
		
		// 判断IP版本并生成相应内容
		ip := net.ParseIP(clientIP)
		if ip == nil {
			c.String(http.StatusOK, "无法获取有效IP")
			return
		}
		
		var ipVersion int
		var nextURL string
		
		if ip.To4() != nil {
			// IPv4地址
			ipVersion = 4
			nextURL = api.Urls6 // 显示IPv6地址的跳转链接
		} else if ip.To16() != nil {
			// IPv6地址
			ipVersion = 6
			nextURL = api.Urls4 // 显示IPv4地址的跳转链接
		} else {
			c.String(http.StatusOK, "无法识别IP版本")
			return
		}
		
		c.String(http.StatusOK, api.GetIndexHtml(clientIP, api.Bg, nextURL, fmt.Sprintf("%d", ipVersion)))
	})
}

// getClientIP 获取客户端真实IP地址
func (api *Server) getClientIP(c *gin.Context) string {
	// 优先检查代理头
	headers := []string{
		"X-Forwarded-For",
		"X-Real-IP",
		"X-Client-IP",
		"CF-Connecting-IP",
		"True-Client-IP",
	}
	
	for _, header := range headers {
		if ip := c.GetHeader(header); ip != "" {
			// 处理X-Forwarded-For可能包含多个IP的情况
			ips := strings.Split(ip, ",")
			if len(ips) > 0 {
				return strings.TrimSpace(ips[0])
			}
		}
	}
	
	// 使用gin的ClientIP作为备选
	return c.ClientIP()
}
